const db = wx.cloud.database()
const _ = db.command
const categoryCollection = db.collection('category')
/**
 * 获取分类列表
 * @param params 查询参数
 * @returns 分类列表
 */
export const getCategories = async (params : any = {}) => {
	let { keyword = '', type = 0, page, pageSize } = params;
	let where : any = {}
	let categoryList = []
	try {
		// 构建查询条件
		if (type) {
			if (typeof type !== 'number') type = parseInt(type)
			where = { type }
		}
		if (keyword) {
			where = { ...where, name: db.RegExp({ regexp: keyword }) }
		}
		if (!where.type && !where.name) {
			where = { name: _.exists(true) }
		}
		// 执行查询
		if (!page && !pageSize) {
			for (var i = 0; ; i += 20) {
				const { data: list } = await categoryCollection.where(where).orderBy('sort', 'asc').orderBy('createTime', 'desc').skip(i).limit(20).get()
				if (list.length === 0) break
				categoryList.push(...list)
				if (list.length < 20) break
			}
		} else {
			const skip = (page - 1) * pageSize;
			({ data: categoryList } = await categoryCollection.where(where)
				.orderBy('sort', 'asc')
				.orderBy('createTime', 'desc')
				.skip(skip)
				.limit(pageSize)
				.get());
		}
		return categoryList;
	} catch (err) {
		console.error('获取员工列表失败:', err)
		wx.showToast({ title: err.message || '查询分类列表失败', icon: 'none' })
		throw err
	}
};

/**
 * 添加分类
 * @param category 分类数据
 * @returns 添加结果
 */
export const addCategory = async (category : any) => {
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		const res = await categoryCollection.add({
			data: {
				...category,
				createTime: db.serverDate(),
				updateTime: db.serverDate(),
			}
		});
		wx.hideLoading()
		return res._id;
	} catch (error) {
		wx.hideLoading()
		if ((error as any).errMsg && (error as any).errMsg.includes("Duplicate")) {
			wx.showToast({ title: '名称重复', icon: 'error' })
		} else {
			wx.showToast({ title: error.message || '添加失败', icon: 'none' })
		}
		console.error('添加分类失败:', error);
		throw error;
	}
};

/**
 * 更新分类
 * @param category 分类数据
 * @returns 更新结果
 */
export const updateCategory = async (category : any) => {
	const { _id, ...data } = category;
	try {
		wx.showLoading({ title: '更新中...', mask: true })
		if (data.name) {
			// 检查name有没有修改
			const { data: { name } } = await categoryCollection.doc(_id).field({ name: true, _id: false }).get()
			if (name !== data.name) {
				const { total } = await categoryCollection.where({ name: data.name }).count()
				if (total) {
					throw new Error('名称重复')
				}
				const { data: list } = await db.collection('dish').field({ _id: true }).where({ categoryId: _id }).get()
				await Promise.all(list.map(item => db.collection('dish').doc(item._id).update({ data: { categoryName: data.name } })))
			}
		}
		const res = await categoryCollection.doc(_id).update({
			data: {
				...data,
				updateTime: db.serverDate(),
			}
		});
		wx.hideLoading()
		return res;
	} catch (error) {
		wx.hideLoading()
		wx.showToast({ title: error.message || '更新失败', icon: 'error' })
		console.error('更新分类失败:', error);
		throw error;
	}
};

/**
 * 删除分类
 * @param id 分类ID
 * @returns 删除结果
 */
export const deleteCategory = async (id : string) => {
	try {
		wx.showLoading({ title: '删除中...', mask: true })
		const { total: dishs } = await db.collection('dish').where({ categoryId: id }).count()
		const { total: setmeals } = await db.collection('setmeal').where({ categoryId: id }).count()
		if (dishs > 0 || setmeals > 0) {
			throw new Error('当前分类下有菜品或套餐，不能删除')
		}
		const res = await db.collection('category').doc(id).remove();
		wx.hideLoading()
		return res;
	} catch (error) {
		wx.hideLoading()
		wx.showToast({ title: error.message || '删除失败', icon: 'none' })
		console.error('删除分类失败:', error);
		throw error;
	}
};